<?php

class SiteController extends Controller
{
	
	public function accessRules(){
        return array(
            array('allow',
                'users'=>array('*'),
            ),
            array('allow',
                'actions'=>array('admin'),
                'expression' => 'Yii::app()->user->getState("isAdmin")',
            ),
        );
    }

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
            'fileUploaderConnector' => "ext.ezzeelfinder.ElFinderConnectorAction",
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		if (Yii::app()->user->getState("isAdmin"))
		{
			$this->actionAdmin();
		}
		else
		{
			$uploadModel = new UploadForm();
			$uploadModel->type = "file";
			if(isset($_POST['UploadForm']))
				$uploadModel->attributes=$_POST['UploadForm'];

			// if it is ajax validation request
			if(isset($_POST['ajax']) && $_POST['ajax']==='upload-form')
			{
				$uploadModel->filename = CUploadedFile::getInstance($uploadModel, 'filename');
				echo CActiveForm::validate($uploadModel);
				Yii::app()->end();
			}

			if(isset($_POST['UploadForm']))
			{
				$lastUpload = Yii::app()->user->getState("lastUpload");
				$nextUpload = Yii::app()->user->isGuest ? $lastUpload+Yii::app()->params["uploadTimeoutGuest"] : $lastUpload+Yii::app()->params["uploadTimeoutAuth"];
				if (time() < $nextUpload)
				{
					Yii::app()->user->setFlash('error', Yii::t('module_file', 'Next upload at %s', array("%s"=>date("Y-m-d H:i:s", $nextUpload))));
				}
				else
				{
					$uploadModel->attributes = $_POST['UploadForm'];
					$uploadModel->filename = CUploadedFile::getInstance($uploadModel, 'filename');
					/* check upload limit */

					// validate user input and redirect to the previous page if valid
					if($uploadModel->validate())
					{
						$filesModel = new Files();
						$filesModel->prepareFile($uploadModel);
						if ($filesModel->save(false))
						{
							if ($uploadModel->type == "message")
							{
								Google::trackSendMessage();
								$message = Yii::t('module_file', 'Message sent.');
							}
							else
							{
								Google::trackSendFile();
								$message = Yii::t('module_file', 'File uploaded.');
							}
							
							$uploadModel->unsetAttributes();
							$uploadModel->type = "file";
							Yii::app()->user->setState("lastUpload", time());
							Yii::app()->user->setFlash('success', $message);
						}
					}
				}
			}
			
			
			if (Yii::app()->user->isGuest)
			{
				$this->render('index', array('uploadModel'=>$uploadModel));
			}
			else
			{
				$model = new Files('search');
				$model->unsetAttributes();
				$model->setAttribute('recipientId', Yii::app()->user->id);
				
				if(isset($_GET['Files']))
					$model->attributes=$_GET['Files'];
				
				$this->render('index-user', array('model'=>$model, 'uploadModel'=>$uploadModel));
			}
		}
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
			{
				if(Yii::app()->user->getState('isAdmin'))
				{
					$this->redirect(array('site/index'));
					Yii::app()->end();
				}
				
				Google::trackLogin();
				
				if(Yii::app()->user->isGuest)
				{
					$this->redirect(Yii::app()->user->returnUrl);
				} 
				else 
				{
					if(!Yii::app()->user->getState('returnedUrl'))
					{
						$this->redirect(array('/site/index'));
					}
					else
					{
						$this->redirect(Yii::app()->user->getState('returnedUrl'));
					}
				}
			}
		}
		// display the login form
		$this->renderPartial('login',array('model'=>$model), false, true);
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionAdmin()
	{
		$this->layout = "//layouts/column1";
		Yii::app()->theme=param('adminTheme');
		$statistics = array(
			tt('Users', 'User') => User::model()->count(),
		);
		$this->render('admin', array('statistics'=>$statistics));
	}
        
        public function actionApiRegister(){
            $return = array('error' => '', 'status' => '', 'data' => '');
            $model_name = 'User';
            $model = new $model_name;
            $model->scenario = 'api';
            if (isset($_REQUEST['username']) && isset($_REQUEST['email']) && isset($_REQUEST['password']))
            {
                //$model->attributes=$_REQUEST[$model_name];
                $model->attributes = array('username' => $_REQUEST['username'], 
                                           'password' => $_REQUEST['password'],
                                           'email' => $_REQUEST['email']);
                if($model->validate()){
                    $model->setPassword();
                    $model->setStatus();
                    $model->save(false);
                    
                    $login_model=new LoginForm;
                    $login_model->attributes = array('username' => $_REQUEST['username'], 'password' => $_REQUEST['password']);
                    if($login_model->login()){
                        $token=new Tokens;
                        //
                        $id = Yii::app()->user->getId();
                        $token->deleteUserTokens($id);
                        $t = $token->generateToken();
                        $token->setIsNewRecord(true);
                        $token->id_user = $id;
                        $token->token = $t;
                        //$token->life_time = time();
                        $token->save(false);
                        //echo 'id:'.$model->i;
                        $return['status'] = 200; 
                        $return['data'] = array('token' => $t);
                    } else {
                        $return['status'] = 401; 
                        $return['error'] = $login_model->getErrors();
                    }
                } else {
                    if ($model->isUserExist($_REQUEST['username'], $_REQUEST['email'])){
                        $return['status'] = 409; 
                    } else {
                        $return['status'] = 401; 
                    }
                    $return['error'] = $model->getErrors();
                }
            }else {
                    $return['status'] = 401; 
                    $return['error'] = 'auth fail';
            }
            echo json_encode($return);
        }
        
	public function actionGetToken(){
		$return = array('error' => '', 'status' => '', 'data' => '');
		if (isset($_REQUEST['username']) && isset($_REQUEST['password'])){
			$model=new LoginForm;
			
                        $model->attributes = array('username' => $_REQUEST['username'], 'password' => $_REQUEST['password']);
			if($model->validate() && $model->login()){
                            $token=new Tokens;
                            //
                            $id = Yii::app()->user->getId();
                            $token->deleteUserTokens($id);
                            $t = $token->generateToken();
                            $token->setIsNewRecord(true);
                            $token->id_user = $id;
                            $token->token = $t;
                            //$token->life_time = time();
                            $token->save(false);
                            //echo 'id:'.$model->i;
                            $return['status'] = 200; 
                            $return['data'] = array('token' => $t);
			} else {
                            $return['status'] = 401; 
                            $return['error'] = $model->getErrors();
                        }
                        
		} else {
                        $return['status'] = 401; 
			$return['error'] = 'auth fail';
		}
		
		echo json_encode($return);
	}
	
	
	public function actionDownload($user = null, $filename = null)
	{
		$command = Yii::app()->db->createCommand("SELECT * FROM {{files}} WHERE recipientId = :userId AND filename = :filename");
		$command->bindParam(":userId", $user, PDO::PARAM_INT);
		$command->bindParam(":filename", $filename, PDO::PARAM_STR);
		$file = $command->queryRow();
		
		$path = Yii::app()->createAbsoluteUrl("/uploads")."/".$file["recipientId"]."/".$file["path"];
		if ($f = fopen($path, "r"))
		{
			header("Content-type: application/octet-stream");
			header("Content-Disposition: filename=\"".$file["filename"]."\"");
			header("Content-length: ".$file["fileSize"]);
			header("Cache-control: private"); //use this to open files directly
			while(!feof($f)) {
			$buffer = fread($f, 2048);
			echo $buffer;
			}
		}
		fclose($f);
		exit;
	}
	
	private function send_google($order)
	{
		if (!empty($order->google_data))
		{
			$google_data = unserialize($order->google_data);
			try
			{
				$tracker = new GoogleAnalytics\Tracker('UA-26183021-1', '.just.travel');
				
				$campaign = new GoogleAnalytics\Campaign('direct');
				$campaign->setSource($google_data['utm_source']);
				$campaign->setName($google_data['utm_ccn']);
				$campaign->setMedium($google_data['utm_medium']);
				$campaign->setContent($google_data['utm_content']);
				$tracker->setCampaign($campaign);

				$visitor = new GoogleAnalytics\Visitor();
				$visitor->setIpAddress($google_data['ip_address']);
				$visitor->setUserAgent($google_data['user_agent']);

				$session = new GoogleAnalytics\Session();

				$transaction = new GoogleAnalytics\Transaction();
				$transaction->setOrderId($order['transaction_id']);
				$transaction->setTotal($order['amount']);
				$transaction->setTax('5% от стоимости');

				$criteria=new CDbCriteria;
				$criteria->condition = 'transaction_id='.$order->transaction_id;
				$tickets = Tickets::model()->findAll($criteria);
				
				foreach ($tickets as $ticket)
				{
					$item = new GoogleAnalytics\Item();
					$item->setOrderId($ticket['transaction_id']);
					$item->setSku($ticket['TicketId']);
					if (!empty($ticket['AgentInfo']))
					{
						switch ($ticket['AgentInfo'])
						{
							case "JT_GIFT":
								$item->setName('AeroexpressFree');
								break;
							case "JT_DISCOUNT":
								$item->setName('AeroexpressSale');
								break;
							default:
								$item->setName('Aeroexpress');
								break;
						}
					}
					else
					{
						$item->setName('Aeroexpress');
					}
					$item->setVariation('econom');
					$item->setPrice(number_format($ticket['Sum'], '2', '.', ''));
					$item->setQuantity(1);
					$transaction->addItem($item);
				}	

				$tracker->trackTransaction($transaction, $session, $visitor);
				
				$actionLog = new ActionLog();
				$actionLog->save('GoogleTrack', $order->transaction_id, $order);
			}
			catch (Exception $e)
			{
				$errorLog = new ErrorLog();
				$errorLog->save('GoogleTrack', $e, $e->getMessage());
			}
		}
	}
	
	
}
